/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import entities.Submission;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Contest;
import entities.User;
import entities.Problem;
import entities.Run;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author santiagobaldrich
 */
public class SubmissionJpaController {

    public SubmissionJpaController()
    {
        emf = Persistence.createEntityManagerFactory("UNOJModelPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Submission submission)
    {
        if (submission.getRunCollection() == null)
        {
            submission.setRunCollection(new ArrayList<Run>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Contest contest = submission.getContest();
            if (contest != null)
            {
                contest = em.getReference(contest.getClass(), contest.getIdContest());
                submission.setContest(contest);
            }
            User user = submission.getUser();
            if (user != null)
            {
                user = em.getReference(user.getClass(), user.getIdUser());
                submission.setUser(user);
            }
            Problem problem = submission.getProblem();
            if (problem != null)
            {
                problem = em.getReference(problem.getClass(), problem.getIdProblem());
                submission.setProblem(problem);
            }
            Collection<Run> attachedRunCollection = new ArrayList<Run>();
            for (Run runCollectionRunToAttach : submission.getRunCollection())
            {
                runCollectionRunToAttach = em.getReference(runCollectionRunToAttach.getClass(), runCollectionRunToAttach.getIdRun());
                attachedRunCollection.add(runCollectionRunToAttach);
            }
            submission.setRunCollection(attachedRunCollection);
            em.persist(submission);
            if (contest != null)
            {
                contest.getSubmissionCollection().add(submission);
                contest = em.merge(contest);
            }
            if (user != null)
            {
                user.getSubmissionCollection().add(submission);
                user = em.merge(user);
            }
            if (problem != null)
            {
                problem.getSubmissionCollection().add(submission);
                problem = em.merge(problem);
            }
            for (Run runCollectionRun : submission.getRunCollection())
            {
                Submission oldSubmissionOfRunCollectionRun = runCollectionRun.getSubmission();
                runCollectionRun.setSubmission(submission);
                runCollectionRun = em.merge(runCollectionRun);
                if (oldSubmissionOfRunCollectionRun != null)
                {
                    oldSubmissionOfRunCollectionRun.getRunCollection().remove(runCollectionRun);
                    oldSubmissionOfRunCollectionRun = em.merge(oldSubmissionOfRunCollectionRun);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Submission submission) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Submission persistentSubmission = em.find(Submission.class, submission.getIdSubmission());
            Contest contestOld = persistentSubmission.getContest();
            Contest contestNew = submission.getContest();
            User userOld = persistentSubmission.getUser();
            User userNew = submission.getUser();
            Problem problemOld = persistentSubmission.getProblem();
            Problem problemNew = submission.getProblem();
            Collection<Run> runCollectionOld = persistentSubmission.getRunCollection();
            Collection<Run> runCollectionNew = submission.getRunCollection();
            List<String> illegalOrphanMessages = null;
            for (Run runCollectionOldRun : runCollectionOld)
            {
                if (!runCollectionNew.contains(runCollectionOldRun))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Run " + runCollectionOldRun + " since its submission field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (contestNew != null)
            {
                contestNew = em.getReference(contestNew.getClass(), contestNew.getIdContest());
                submission.setContest(contestNew);
            }
            if (userNew != null)
            {
                userNew = em.getReference(userNew.getClass(), userNew.getIdUser());
                submission.setUser(userNew);
            }
            if (problemNew != null)
            {
                problemNew = em.getReference(problemNew.getClass(), problemNew.getIdProblem());
                submission.setProblem(problemNew);
            }
            Collection<Run> attachedRunCollectionNew = new ArrayList<Run>();
            for (Run runCollectionNewRunToAttach : runCollectionNew)
            {
                runCollectionNewRunToAttach = em.getReference(runCollectionNewRunToAttach.getClass(), runCollectionNewRunToAttach.getIdRun());
                attachedRunCollectionNew.add(runCollectionNewRunToAttach);
            }
            runCollectionNew = attachedRunCollectionNew;
            submission.setRunCollection(runCollectionNew);
            submission = em.merge(submission);
            if (contestOld != null && !contestOld.equals(contestNew))
            {
                contestOld.getSubmissionCollection().remove(submission);
                contestOld = em.merge(contestOld);
            }
            if (contestNew != null && !contestNew.equals(contestOld))
            {
                contestNew.getSubmissionCollection().add(submission);
                contestNew = em.merge(contestNew);
            }
            if (userOld != null && !userOld.equals(userNew))
            {
                userOld.getSubmissionCollection().remove(submission);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld))
            {
                userNew.getSubmissionCollection().add(submission);
                userNew = em.merge(userNew);
            }
            if (problemOld != null && !problemOld.equals(problemNew))
            {
                problemOld.getSubmissionCollection().remove(submission);
                problemOld = em.merge(problemOld);
            }
            if (problemNew != null && !problemNew.equals(problemOld))
            {
                problemNew.getSubmissionCollection().add(submission);
                problemNew = em.merge(problemNew);
            }
            for (Run runCollectionNewRun : runCollectionNew)
            {
                if (!runCollectionOld.contains(runCollectionNewRun))
                {
                    Submission oldSubmissionOfRunCollectionNewRun = runCollectionNewRun.getSubmission();
                    runCollectionNewRun.setSubmission(submission);
                    runCollectionNewRun = em.merge(runCollectionNewRun);
                    if (oldSubmissionOfRunCollectionNewRun != null && !oldSubmissionOfRunCollectionNewRun.equals(submission))
                    {
                        oldSubmissionOfRunCollectionNewRun.getRunCollection().remove(runCollectionNewRun);
                        oldSubmissionOfRunCollectionNewRun = em.merge(oldSubmissionOfRunCollectionNewRun);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = submission.getIdSubmission();
                if (findSubmission(id) == null)
                {
                    throw new NonexistentEntityException("The submission with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Submission submission;
            try
            {
                submission = em.getReference(Submission.class, id);
                submission.getIdSubmission();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The submission with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Run> runCollectionOrphanCheck = submission.getRunCollection();
            for (Run runCollectionOrphanCheckRun : runCollectionOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Submission (" + submission + ") cannot be destroyed since the Run " + runCollectionOrphanCheckRun + " in its runCollection field has a non-nullable submission field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Contest contest = submission.getContest();
            if (contest != null)
            {
                contest.getSubmissionCollection().remove(submission);
                contest = em.merge(contest);
            }
            User user = submission.getUser();
            if (user != null)
            {
                user.getSubmissionCollection().remove(submission);
                user = em.merge(user);
            }
            Problem problem = submission.getProblem();
            if (problem != null)
            {
                problem.getSubmissionCollection().remove(submission);
                problem = em.merge(problem);
            }
            em.remove(submission);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Submission> findSubmissionEntities()
    {
        return findSubmissionEntities(true, -1, -1);
    }

    public List<Submission> findSubmissionEntities(int maxResults, int firstResult)
    {
        return findSubmissionEntities(false, maxResults, firstResult);
    }

    private List<Submission> findSubmissionEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Submission.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Submission findSubmission(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Submission.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getSubmissionCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Submission> rt = cq.from(Submission.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public List<Submission> findSubmissionsByUser(User user)
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            Query q = em.createQuery("Select s from Submission s where s.user =:user");
            q.setParameter("user", user);
            return (List<Submission>)q.getResultList();
        }
        catch (Exception e)
        {
            System.out.println("EX: " + e.getMessage());
            return null;
        }
    }

}
